package com.huiruan.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huiruan.dto.LoginDTO;
import com.huiruan.dto.WxLoginDTO;
import com.huiruan.entity.MiniUser;
import com.huiruan.entity.SysUser;
import com.huiruan.exception.CustomException;
import com.huiruan.mapper.MiniUserMapper;
import com.huiruan.mapper.SysUserMapper;
import com.huiruan.service.AuthService;
import com.huiruan.utils.*;
import com.huiruan.vo.CaptchaVO;
import com.huiruan.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 认证服务实现类
 */
@Service
public class AuthServiceImpl implements AuthService {
    private final SysUserMapper sysUserMapper;
    private final MiniUserMapper miniUserMapper;

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Value("${wx.login-url}")
    private String loginUrl;
    @Value("${jwt.token-prefix}")
    private  String tokenType;
    public AuthServiceImpl(SysUserMapper sysUserMapper, MiniUserMapper miniUserMapper) {
        this.sysUserMapper = sysUserMapper;
        this.miniUserMapper = miniUserMapper;
    }

    @Override
    public Result<CaptchaVO> generateCaptcha() {
        // 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40, 4, 50);

        // 生成验证码key
        String captchaKey = UUID.randomUUID().toString();

        // 验证码存入redis，有效期5分钟
        RedisUtil.set("captcha:" + captchaKey, lineCaptcha.getCode(), 5, TimeUnit.MINUTES);

        // 返回验证码信息
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaKey(captchaKey);
        captchaVO.setCapthaCode(lineCaptcha.getCode());
        captchaVO.setCaptchaImage(lineCaptcha.getImageBase64());

        return Result.success(captchaVO);
    }

    @Override
    public Result<LoginVO> login(LoginDTO loginDTO) {
        // 验证验证码
        String captchaCode = (String) RedisUtil.get("captcha:" + loginDTO.getCaptchaKey());
        if (StrUtil.isEmpty(captchaCode)) {
            return Result.failed(ResultCode.CAPTCHA_EXPIRE);
        }
        if (!captchaCode.equalsIgnoreCase(loginDTO.getCaptchaCode())) {
            return Result.failed(ResultCode.CAPTCHA_ERROR);
        }

        // 查询用户
        SysUser sysUser = sysUserMapper.selectByUsername(loginDTO.getUsername());
        if (sysUser == null) {
            return Result.failed(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }

        // 验证密码
        if (!sysUser.getPassword().equals(DigestUtil.md5Hex(loginDTO.getPassword()))) {
            return Result.failed(ResultCode.USER_ACCOUNT_PASSWORD_ERROR);
        }

        // 验证账号状态
        if (sysUser.getStatus() != 1) {
            return Result.failed(ResultCode.USER_ACCOUNT_DISABLED);
        }

        // 生成token
        String token = JwtUtil.generateToken(sysUser.getId(), "pc");

        // 返回登录信息
        LoginVO loginVO = new LoginVO();
        loginVO.setAccessToken(token);
        loginVO.setTokenType(tokenType);
        loginVO.setUsername(sysUser.getUserName());
        loginVO.setNickname(sysUser.getNickName());

        // 删除验证码
        RedisUtil.delete("captcha:" + loginDTO.getCaptchaKey());

        return Result.success(loginVO);
    }

    @Override
    public Result<LoginVO> wxLogin(WxLoginDTO wxLoginDTO) {
        // 构建请求URL
        String url = StrUtil.format("{}?appid={}&secret={}&js_code={}&grant_type=authorization_code",
                loginUrl, appId, appSecret, wxLoginDTO.getCode());

        // 请求微信接口
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 判断是否请求成功
        if (jsonObject.containsKey("errcode")) {
            return Result.failed(ResultCode.WX_LOGIN_FAILED);
        }

        // 获取openid
        String openId = jsonObject.getStr("openid");

        // 查询用户是否存在
        MiniUser miniUser = miniUserMapper.selectByOpenId(openId);

        // 如果用户不存在，则创建新用户
        if (miniUser == null) {
            miniUser = new MiniUser();
            miniUser.setOpenId(openId);
            miniUser.setNickname("微信用户");
            miniUserMapper.insert(miniUser);
        }

        // 生成token
        String token = JwtUtil.generateToken(miniUser.getId(), "mini");

        // 返回登录信息
        LoginVO loginVO = new LoginVO();
        loginVO.setAccessToken(token);
        loginVO.setTokenType(tokenType);
        loginVO.setUsername(miniUser.getOpenId());
        loginVO.setNickname(miniUser.getNickname());

        return Result.success(loginVO);
    }
}
